// pages/paySocial/paySocial.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tipsFlag: false,
    comfirmMakeUpFlag: false,//是否补缴 判断
    makeUpFlag: false, //补缴弹框
    firstIndex: 2, //本城市参保情况  true 首次 1 false 缴过 2
    agreeFlag: true, //相关协议
    DetailsFlag: false, //社保明细弹框
    cityIndex: 0, //选择城市的下标
    allIndex: 0, //社保类型
    scaleIndex: 1, //公积金比例下标
    month: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], //改，增加多月份
    monthIndex: 0, //固定缴纳下标，增加多月份
    beginArray: [1, 2, 3, 4, 5],
    endArray: [1, 2, 3, 4, 5],
    startIndex: 0, //补缴月份的下标
    endIndex: 0,
    pictureUrl: '/image/',
    switchChecked: true, //是否缴纳公积金
    scrollToView: '',
    same_startIndex: 0,
    socialDetail: {}, //社保明细
    gongjijinVal: '', //公积金基数
    showWarn: false, //提示公积金需填写
    taxPayment: [],
    background:"",
    isShow: false
  },
  scroll(e){
    let scrollHeight = e.detail.scrollTop
    if(scrollHeight > 30){
      this.setData({
        background:'#FFA418'
      })
    }else{
      this.setData({
        background:'transparent'
      })
    }
  },
  // 确定补缴
  comfirmMakeUpBtn() {
    this.setData({
      makeUpFlag: false,
      comfirmMakeUpFlag: true,
      same_startIndex: this.data.startIndex
    })
  },
  // 选择补缴月份
  makeUpChange(e) {
    console.log(e)
    this.setData({
      startIndex: e.detail.value
    })
  },
  // 补缴点击取消
  cancleMakeUpBtn() {
    this.setData({
      makeUpFlag: false
    })
  },
  // 输入公积金
  moneyBtn(e) {
    this.setData({
      gongjijinVal: e.detail.value
    })
  },
  // 缴纳最低金额
  minimumBtn() {
    this.setData({
      gongjijinVal: this.data.list[this.data.cityIndex].gongjijin_min_base
    })
  },
  // 我要补缴
  makeUp() {
    this.setData({
      makeUpFlag: true
    })
  },
  // 同意相关条约
  agreeBtn() {
    this.setData({
      agreeFlag: !this.data.agreeFlag
    })
  },
  // 查看相关条约
  readRules() {
    wx.showLoading({
      title: '等待中',
      mask: true
    })
    wx.navigateTo({
      url: '../rules/rules',
    }, wx.hideLoading())
  },
  tipConfirm() {
    this.comfirmOrder(this.data.query)
  },
  // 确认
  next() {
    let msg = {
      city_code: this.data.list[this.data.cityIndex].city_code, //城市id
      cityname: this.data.list[this.data.cityIndex].name, //城市名字
      is_new: this.data.firstIndex, //是否新参保
      stid: this.data.list[this.data.cityIndex].shebao_types[this.data.allIndex].id, //社保类型
      count: this.data.comfirmMakeUpFlag ? (this.data.taxPayment.length - this.data.startIndex) : this.data.month[this.data.monthIndex],
      start_date: this.data.comfirmMakeUpFlag ? (this.data.comparTimeList[this.data.same_startIndex]) : this.data.same_month
    }
    if (this.data.comfirmMakeUpFlag) {
      msg.bujiao = 1
    }
    if (this.data.switchChecked) {
      if (this.data.gongjijinVal == '') {
        this.setData({
          showWarn: true,
          scrollToView: 'gongjijin',
        })
        setTimeout(() => {
          this.setData({
            showWarn: false
          })
        }, 1000)
        return
      } else {
        let min_base = this.data.list[this.data.cityIndex].gongjijin_min_base * 100
        let max_base = this.data.list[this.data.cityIndex].gongjijin_max_base * 100
        let compareVal = this.data.gongjijinVal * 100
        if (compareVal >= min_base && compareVal <= max_base) {
          if (this.data.list[this.data.cityIndex].gongjijin_types[this.data.scaleIndex]) {
            msg.gtid = this.data.list[this.data.cityIndex].gongjijin_types[this.data.scaleIndex].id
          }
          msg.base = compareVal / 100
          msg.gongjijin = 1
        } else {
          wx.showToast({
            title: '缴纳的金额不在范围内', //提示文字
            duration: 1000, //显示时长
            mask: true, //是否显示透明蒙层，防止触摸穿透，默认：false  
            icon: 'none', //图标，支持"success"、"loading"  
          })
          return
        }
      }
    } else {
      msg.gtid = ''
      msg.base = ''
      msg.gongjijin = 0
    }
    if (this.data.agreeFlag) {
      console.log(msg)
      let query = JSON.stringify(msg)
      this.setData({
        query
      })
      let agreeShow = wx.getStorageSync('agreeShow')
      if (agreeShow) {
        console.log("同意了")
      } else {
        console.log("需要提醒用户")
        this.setData({
          tipsFlag: true
        })
        return
      }
      wx.nextTick(() =>{
        this.comfirmOrder(query)
      })
    } else {
      wx.showModal({
        content: '您需要同意相关协议',
        showCancel: false
      })
    }
  },
  comfirmOrder(query) {
    wx.showLoading({
      title: '等待中',
      mask: true
    })
    wx.navigateTo({
      url: `../addUser/addUser?query=${query}&fromto=social`,
    }, wx.hideLoading())
  },
  // 社保类型
  bindAllChange(e) {
    let idx = this.data.cityIndex
    let sortIdx = e.detail.value
    let socialDetail = {
      total: this.data.list[idx].shebao_types[sortIdx].amount,
      detail: this.data.list[idx].shebao_types[sortIdx].detail,
    }
    this.setData({
      monthIndex: 0,
      allIndex: sortIdx,
      socialDetail
    })
    let id = this.data.list[idx].shebao_types[sortIdx].id
    this.obtainSocialData(id)
  },

  // 选择缴纳多久月份
  bindMonthChange(e) {
    this.setData({
      comfirmMakeUpFlag: false,
      monthIndex: Number(e.detail.value)
    })
    wx.nextTick(() => {
      this.time(true, this.data.month[Number(e.detail.value)])
    })

  },
  // 选择公积金比例
  bindScaleChange(e) {
    this.setData({
      scaleIndex: e.detail.value
    })
  },
  // 交付若干月
  paySomeMonth(e) {
    const monthidx = e.currentTarget.dataset.monthidx;
    this.setData({
      comfirmMakeUpFlag: false,
      monthIndex: Number(monthidx)
    })
    wx.nextTick(() => {
      this.time(true, this.data.month[Number(monthidx)])
    })
  },
  // 缴纳月份选择
  // 缴纳一个月
  payOneMonth() {
    this.setData({
      monthIndex: 0,
    })
  },
  // 缴纳三个月
  payThreeMonth() {
    this.setData({
      monthIndex: 1,
    })
  },
  // 缴纳六个月
  paySixMonth() {
    this.setData({
      monthIndex: 2,
    })
  },
  // 缴纳12个月
  payTwelveMonth() {
    this.setData({
      monthIndex: 3,
    })
  },
  // 选择缴纳城市
  bindCityChange(e) {
    let socialDetail = {
      total: this.data.list[e.detail.value].shebao_types[0].amount,
      detail: this.data.list[e.detail.value].shebao_types[0].detail,
    }
    this.setData({
      comfirmMakeUpFlag: false,
      monthIndex: 0,
      cityIndex: e.detail.value,
      allIndex: 0,
      scaleIndex: 0,
      startIndex: 0,
      socialDetail
    })
    let id = this.data.list[e.detail.value].shebao_types[0].id
    this.obtainSocialData(id)

    if(this.data.list[this.data.cityIndex].city_code == 'beijing' || this.data.list[this.data.cityIndex].city_code == 'suzhoushiqu'){
      this.setData({
        isShow: true,
        switchChecked: true,
        gongjijinVal: this.data.list[this.data.cityIndex].gongjijin_min_base
      })

    }else{
      this.setData({
      isShow: false,
      gongjijinVal: this.data.list[this.data.cityIndex].gongjijin_min_base
    })}
  },

  // 点击查看社保明细
  socialDetails() {
    this.setData({
      DetailsFlag: true
    })
  },
  // 是否缴纳公积金
  switchChange(e) {
    if(this.data.list[this.data.cityIndex].city_code == 'beijing' || this.data.list[this.data.cityIndex].city_code == 'suzhoushiqu' || this.data.list[this.data.cityIndex].city_code == 'suzhouyuanqu'){
      this.setData({
        switchChecked:true,
        disabled: true,
        isShow: true
      })
    }else{
      this.setData({
      switchChecked: e.detail.value,
      isShow: false
    })}
  },
  // 我想多交点
  morePay() {
    if (this.data.agreeFlag) {
      let msg = {
        city_code: 'bu', //城市id
      }
      let query = JSON.stringify(msg)
      wx.showLoading({
        title: '等待中',
        mask: true
      })
      wx.navigateTo({
        url: `../addUser/addUser?query=${query}&fromto=social`,
      }, wx.hideLoading())
    } else {
      wx.showModal({
        content: '您需要同意相关协议',
        showCancel: false
      })
    }
  },
  // 参保情况
  firstBtn() {
    this.setData({
      firstIndex: 1
    })
  },
  secondBtn() {
    this.setData({
      firstIndex: 2
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    // 获取每个城市的社保详情
    app.request("daijiao/shebao", {}, true).then(res => {
      if (res.error_code == 0) {
        let arr = res.data;
        // 获取默认城市（北京）的社保总金额和社保详情
        let socialDetail = {
          total: arr[0].shebao_types[0].amount,
          detail: arr[0].shebao_types[0].detail,
        };
        // 
        app.request('daijiao/gongjijin', {}, true).then(res => {
          console.log('-----daijiao/gongjijin-----')
          console.log(res.data)
          if (res.error_code == 0) {
            // 根据公积金缴纳比例获取数据
            this.obtainSocialData(arr[0].shebao_types[0].id)
            let gongjijin = res.data
            for (let i in arr) {
              for (let j in gongjijin) {
                if (arr[i].city_code == gongjijin[j].city_code) {
                  arr[i].gongjijin_types = gongjijin[j].gongjijin_types
                  arr[i].gongjijin_min_base = gongjijin[j].min_base
                  arr[i].gongjijin_max_base = gongjijin[j].max_base
                }
              }
            }            
            this.setData({
              list: arr,
              socialDetail,
              userInfo: app.globalData.userInfo,
            },wx.hideLoading())
          }else{
            wx.showModal({
              content: res.error_message,
              showCancel:false
            })
          }
        })
      }else{
        wx.showModal({
          content: res.error_message,
          showCancel:false
        })
      }
    })
  },

  // 获取社保 缴纳截止日期 补缴开始日期 当前日期
  obtainSocialData(id) {
    app.request("daijiao/shebao_data", {
      stid: id,
      bujiao: 1
    }, true).then(res => {
      // wx.hideLoading()
      if (res.error_code == 0) {
        console.log('-----daijiao/shebao_data----')
        console.log(res.data)
        this.setData({
          beginValue: res.data.same_month, //开始时间
          start_date: res.data.start_date, //开始时间
          same_month: res.data.same_month, //当前月份
          end_date: res.data.end_date, //结束时间
          gongjijinVal:this.data.list[this.data.cityIndex].gongjijin_min_base, // 最小充值金额
        })
        let sMonth = null
        let eMonth = null
        let nowYear = res.data.same_month.split('-')[0]


        let beginMonth = res.data.start_date.split('-')[1]
        let compareNum = Number(beginMonth.substring(0, 1))

        let endMonth = res.data.end_date.split('-')[1]
        let compareEndNum = Number(endMonth.substring(0, 1))


        sMonth = compareNum >= 0 ? Number(beginMonth.substring(0, 2)) : beginMonth
        eMonth = compareEndNum >= 0 ? Number(endMonth.substring(0, 2)) : endMonth


        this.setData({
          taxPayment: this.chooseList(sMonth, eMonth),
          nowYear: nowYear
        })
        let arr = this.chooseList(sMonth, eMonth)
        this.time(false, arr.length)
        this.compareTime(res.data.start_date, arr.length)
      }else{
        wx.showModal({
          content: res.error_message,
          showCancel:false
        })
      }
    })
  },

  // 补缴 月份区间
  chooseList(firstIndex, lastIndex) {
    let arr = []
    for (let i = firstIndex; i <= lastIndex; i++) {
      arr.push(i)
    }
    return arr
  },
  // 开始 - 结束时间
  time(start = true, index = 1) {
    let comparTime = start ? this.data.beginValue : this.data.start_date
    if (comparTime !== "" && index >= 0) {
      let timeDate = comparTime;
      let date = new Date(timeDate)
      let year = date.getFullYear()
      let month = date.getMonth() + 1;
      let arr = []
      arr.push(year + "-" + this.formatNumber(month))
      for (let i = 1; i < index; i++) {
        month += 1
        if (month > 12) {
          arr.push(parseInt(year) + 1 + "-" + this.formatNumber(parseInt(month - 12)))
        } else {
          arr.push(year + "-" + this.formatNumber(month))
        }
      }
      console.log(arr)
      this.setData({
        arr,
        lastMonth: arr[arr.length - 1]
      })
    }
  },

  // 计算补缴时间
  compareTime(comparTime, index) {
    if (comparTime !== "" && index >= 0) {
      let timeDate = comparTime;
      let date = new Date(timeDate)
      let year = date.getFullYear()
      let month = date.getMonth() + 1;
      let arr = []
      arr.push(year + "-" + this.formatNumber(month))
      for (let i = 1; i < index; i++) {
        month += 1
        if (month > 12) {
          arr.push(parseInt(year) + 1 + "-" + this.formatNumber(parseInt(month - 12)))
        } else {
          arr.push(year + "-" + this.formatNumber(month))
        }
      }
      console.log(arr)
      this.setData({
        comparTimeList: arr
      })
    }
  },

  // 月份处理
  formatNumber(n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      
  }
})